﻿using AbpVnext_Module.Dto;
using AbpVnext_Module.Iservice;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Auditing;
using Volo.Abp.Features;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Users;
using Volo.Abp.VirtualFileSystem;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace AbpVnext_Module.Controllers
{
    [Route("api/[controller]/[action]")]
    //一级权限
    //[Authorize("Product.Mange")]

    //一级特征
    //[RequiresFeature("AddProducrFeature")]

    //多租户含有其中一个特征，则验证通过
    //[RequiresFeature("UpdateProducrFeature", "DeleteProducrFeature")]

    //定义了多少特征，租户必须要有多少特征，否则不能访问
    //[RequiresFeature(RequiresAll = true)]
    [ApiController]
    public class ProductController : AbpController
    {
        public IProductService productService { get; set; }

        public IAuthorizationService _authorizationService { get; set; }

        public ILogger<ProductController> logger { get; set; }

        //多租户
        public ICurrentTenant currentTenant { get; set; }

        public IProductImageService productImageService { get; set; }

        //多租户子特征鉴权 (特征检查接口)
        public IFeatureChecker featureChecker { get; set; }

        /// <summary>
        /// 当前用户
        /// </summary>
        public ICurrentUser currentUser { get; set; }

        /// <summary>
        /// 虚拟头文提供者 接口
        /// </summary>
        public IVirtualFileProvider  VirtualFileProvider { get; set; }        

        public ProductController()
        {

        }

        /// <summary>
        /// 添加 测试接口
        /// </summary>
        /// <param name="product"></param>
        /// <returns></returns>
        //基于特性鉴权 添加多个特性时候 需要多个特性都校验通过才能进入方法
        //与 
        //[Authorize("Product_Select")]
        //[Authorize("Product_Select_Page")]
        //与
        //[Authorize("Product_Select_Page/Product_Select")]
        [HttpPost]
        [Authorize("Product_Select")]
        public async Task<string> InsertProduct([FromBody] PermissionCreateDto product)
        {
            //return productService.InsertProduct(product);
            //AuthorizationResult authenticateResult = await _authorizationService.AuthorizeAsync(HttpContext.User, HttpContext, "Product_Select");

            //基于service授权
            //需要多个权限才能请求接口 ，二级权限
            //await AuthorizationService.CheckAsync("Product_Select_Page");
            //await AuthorizationService.AuthorizeAsync(HttpContext.User, HttpContext, "Product_Select");
            return "";
        }

        /// <summary>
        /// 测试接口
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize("Product_Select")]
        public async Task<string> IgnoreAuthorize()
        {
            logger.LogError("xxxxx");
            logger.LogInformation("xxxxx");
            return "";
        }

        /// <summary>
        /// 测试多租户
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> MultiTenancys()
        {
            //获取多租户id
            var t = currentTenant.Id;

            return "测试成功";
        }

        /// <summary>
        /// 测试多租户权限
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Authorize("Product.Mange.Insert")]
        public async Task<string> MultiTenancysTestZation(ProductImageCreateDto productImageCreateDto)
        {
            //获取多租户id
            //var t = currentTenant.Id;
            //productImageCreateDto.TenantId = currentTenant.Id;

            //使用多租户查询商品
            //await productImageService.GetListAsync(new ProductImagePageDto() { Guid = currentTenant.Id});

            //使用多租户添加商品
            await productImageService.CreateAsync(productImageCreateDto);
            return "测试成功";
        }

        /// <summary>
        /// 多租户特征测试,测试多租户是否有AddProducrGroupFeature特征
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [RequiresFeature("AddProducrFeature")]
        public async Task<string> MultiTGenancysFeature(ProductImageCreateDto productImageCreateDto)
        {
            await productImageService.CreateAsync(productImageCreateDto);
            return "测试成功";
        }

        /// <summary>
        /// 多租户特征测试
        /// </summary>
        /// <param name="productImageCreateDto"></param>
        /// <returns></returns>
        [HttpPost]
        [RequiresFeature("UpdateProducrFeature")]
        public async Task<string> MultiTUpdateProducrFeature(ProductImageCreateDto productImageCreateDto)
        {
            await productImageService.CreateAsync(productImageCreateDto);
            return "测试成功";
        }

        /// <summary>
        /// 多租户特征测试
        /// </summary>
        /// <param name="productImageCreateDto"></param>
        /// <returns></returns>
        [HttpPost]
        [RequiresFeature("DeleteProducrFeature")]  //父特征
        public async Task<string> MultiDeleteProducrFeature(ProductImageCreateDto productImageCreateDto)
        {
            //测试子特征
            await productImageService.CreateAsync(productImageCreateDto);
            //子特征授予，租户 发送短信

            await featureChecker.CheckEnabledAsync("SendSmsFeature");
            var f1 = await featureChecker.IsEnabledAsync("SendSmsFeature");
            if (f1)
            {
                Console.WriteLine("可以发送短信");
            }

            //子特征授予，租户 发送邮件
            await featureChecker.CheckEnabledAsync("SendEmaillFeature");
            var f2 = await featureChecker.IsEnabledAsync("SendEmaillFeature");
            //测试子特征
            if (f2)
            {
                Console.WriteLine("可以发送邮件");
            }
            return "测试成功";
        }

        /// <summary>
        /// 多级权限测试
        /// </summary>
        /// <param name="productImageCreateDto"></param>
        /// <returns></returns>
        //二级特征  一、二级特征 多租户都含有则会验证通过
        //[RequiresFeature("DeleteProducrFeature")]

        //多租户含有其中一个特征，则验证通过
        //[RequiresFeature("UpdateProducrFeature", "DeleteProducrFeature")]
        [HttpPost]
        //[Audited] //开启审计日志记录
        public async Task<string> MultilevelFeatureTest(ProductImageCreateDto productImageCreateDto)
        {
            await productImageService.CreateAsync(productImageCreateDto);
            return "测试成功";
        }

        /// <summary>
        /// 测试虚拟文件系统
        /// </summary>
        /// <param name="productImageCreateDto"></param>
        /// <returns></returns>
        [HttpPost]
        //[Audited] //开启审计日志记录
        public async Task<string> TestVirtualFileSystem(ProductImageCreateDto productImageCreateDto)
        {
            //虚拟文件系统 Ebusiness_Domain  项目测试
            {
                var data = VirtualFileProvider.GetFileInfo("/Localizations/Resources/zh-Hant.json");
                var w = data.ReadBytes();
                var xxw = data.ReadAsString();
                Console.WriteLine(xxw);
            }

            //虚拟文件系统 Ebusiness_Host 项目测试
            {  //基本文件、文件流操作
               //var data = VirtualFileProvider.GetFileInfo("/File/totxt/Sql Server 密码.txt");

                //var data = VirtualFileProvider.GetFileInfo("/File/totxt/IMG_0018(20221109-194531).JPG");
                ////var txt = data.ReadAsString();
                //var x = data.CreateReadStream();
                //var w = data.ReadBytes();
            }
            {
                //一次性读取批量文件
                //IDirectoryContents contents = VirtualFileProvider.GetDirectoryContents("/File/totxt");
                //IEnumerator<IFileInfo> data = contents.GetEnumerator();
                //while (data.MoveNext()) 
                //{
                //    var x = data.Current.CreateReadStream();
                //    var w = data.Current.ReadBytes();
                //}
            }

            {
                //var data = VirtualFileProvider.GetFileInfo("/File/totxt/IMG_0018(20221109-194531).JPG");
                //var x = data.CreateReadStream();
                ////大文件操作
                ////如果文件过大，超过了内存的大小，导致内存溢出异常
                ////分段读取：1t-32g，一次性读取32g，一共读取32次，才能读完
                ////场景：有限资源解决无线资源问题，就i需要使用分段读取 
                ////使用文件流来进行分段
                ////byte[] buffer = new byte[1024 * 1024 * 1024 * 1024 * 32]; // 32gB缓冲区
                //Stream fileStream = new FileStream("D:\\学习\\项目\\Abp_DDD\\abp\\webApi\\Ebusiness_Host\\File\\IMG_0018.JPG", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                //byte[] buffer = new byte[1024 * 4]; // 4KB缓冲区
                //int bytesRead;
                //while ((bytesRead = x.Read(buffer, 0, buffer.Length)) > 0)
                //{
                //    var xr = x.Position;
                //    // 处理当前buffer的数据（仅4KB在内存中）
                //    //读取之后将数据缓存起来
                //    fileStream.Write(buffer, 0, bytesRead);
                //    var ww = fileStream.Position;
                //}
                //await productImageService.CreateAsync(productImageCreateDto);
            }
            return $"测试成功";
        }
    }
}
